package com.emm.yixun.mobile.ui.notice;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetNoticeCategoryList;
import com.emm.yixun.mobile.model.GetNoticeCategoryList.NoticeCategoryList;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.viewpagerindicator.TabPageIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 公告
 * </p>
 * <p>
 * <b>Description：</b> 首页跳转过来，或者通过推送消息进入
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午3:38:35
 */
public class NoticeFragmentActivity extends SwipeBackActivity {

	private static final String TAG = "NoticeFragmentActivity";

	/**
	 * Tab标题
	 */
	ArrayList<NoticeCategoryList> list = new ArrayList<GetNoticeCategoryList.NoticeCategoryList>();

	/** 标题 */
	TextView title_main;

	/** 返回按钮 */
	ImageView back_btn;

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	ViewPager pager;

	/** tab控件 */
	TabPageIndicator indicator;

	/** 界面处理适配器 */
	FragmentPagerAdapter adapter;

	@Override
	protected void onResume() {
		BaseActivity.activity = this;
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notice_fragment_activity);

		// 侧滑关闭框架配置方法
		SetSwipeBackLayout(mSwipeBackLayout);

		BaseActivity.activity = this;
		// 初始化分类
		NoticeCategoryList not = new NoticeCategoryList();
		not.setNoticeCategory("全部分类");
		not.setNoticeCategoryId("999");
		list.add(not);
		initView();
		
		SetRelativiLayoutPadding(R.id.main_head_top_rela);
		
		getNoticeCategoryList();
	}

	private void initView() {
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText(getString(R.string.notice_title));
		back_btn = (ImageView) findViewById(R.id.back_btn);
		// ViewPager的adapter
		pager = (ViewPager) findViewById(R.id.pager);
		// 请求数据后调用
		adapter = new TabPageIndicatorAdapter(getSupportFragmentManager());
		pager.setAdapter(adapter);

		// 实例化TabPageIndicator然后设置ViewPager与之关联
		indicator = (TabPageIndicator) findViewById(R.id.indicator);

		indicator.setViewPager(pager);
		// 如果我们要对ViewPager设置监听，用indicator设置就行了
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 加标记
				EmmApplication.IsReloadMain = true;
				finish();
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 加标记
			EmmApplication.IsReloadMain = true;
			finish();
		} else {
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * ViewPager适配器
	 */
	class TabPageIndicatorAdapter extends FragmentPagerAdapter {
		public TabPageIndicatorAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// 新建一个Fragment来展示ViewPager item的内容，并传递参数
			Fragment fragment = new ItemFragment();
			// 通过bundle传值到fragment界面
			Bundle args = new Bundle();
			args.putString("arg", list.get(position).getNoticeCategory());
			args.putString("ID", list.get(position).getNoticeCategoryId());
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return list.get(position % list.size()).getNoticeCategory();
		}

		@Override
		public int getCount() {
			return list.size();
		}
	}

	/** 查询公告列表接口 */
	GetNoticeCategoryList getnotice;

	/**
	 * <p>
	 * <b>Title：</b> 查询公告列表接口
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月21日 下午3:39:23
	 */
	private void getNoticeCategoryList() {
		EmmApplication.updateUrl("getNoticeCategoryList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("projectCode", EmmApplication.getProjectCode());
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v(TAG, "getNoticeCategoryList-->post:"+ EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.hideDialogForLoading();
				Loading.showDialogForLoading(NoticeFragmentActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, "content:" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getnotice = JSONObject.parseObject(resData.toString(), GetNoticeCategoryList.class);
				if ("1".equals(getnotice.getResult())) {
					Log.v("获取成功", "");
					if (null != getnotice && null != getnotice.getNoticeCategoryList()) {
						list.addAll(getnotice.getNoticeCategoryList());
					}
					// 刷新标题栏以及列表
					adapter.notifyDataSetChanged();
					indicator.notifyDataSetChanged();
				} else {
					EmmApplication.T(getnotice.getErrorMsg().toString());
					try {
						Log.v("获取失败", "getNoticeCategoryList-->errorCode:" + getnotice.getErrorCode().toString()
								+ "errorMsg:" + getnotice.getErrorMsg().toString());
					} catch (NullPointerException e) {
						Log.v(TAG, "getNoticeCategoryList-->客户详情，错误信息获取空指针异常");
						e.printStackTrace();
					}
				}
			}
		});
	}
}
